package middleware

import (
	"strings"

	"gitee.com/huangxinbo/xcas/pkg/i18n"
	"github.com/gin-gonic/gin"
)

// Handler middleware processing function
func (m *Middleware) I18nMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		m.I18n.Locale = i18n.DefaultLocale

		// Get from Accept-Language header
		acceptLanguage := c.GetHeader("Accept-Language")
		if acceptLanguage != "" {
			locales := strings.Split(acceptLanguage, ",")
			if len(locales) > 0 {
				// Take the first language setting
				locale := strings.Split(locales[0], ";")[0]
				m.I18n.Locale = m.normalizeLocale(strings.ToLower(locale))
			}
		}

		c.Next()
	}
}

// normalizeLocale normalizes language code
func (m *Middleware) normalizeLocale(locale string) string {
	locale = strings.TrimSpace(locale)
	locale = strings.ToLower(locale)

	// Supported language mappings
	supportedLocales := map[string]string{
		"zh":      "zh-CN",
		"zh-cn":   "zh-CN",
		"zh-hans": "zh-CN",
		"en":      "en-US",
		"en-us":   "en-US",
		"en-gb":   "en-US", // Default to American English
	}

	if normalized, ok := supportedLocales[locale]; ok {
		return normalized
	}

	// If language code contains region information, try to match
	if len(locale) > 2 && locale[2] == '-' {
		baseLang := locale[:2]
		if normalized, ok := supportedLocales[baseLang]; ok {
			return normalized
		}
	}

	// Default return en-US
	return i18n.DefaultLocale
}
